package com.lvmama.service.system.impl;

import com.lvmama.common.constants.Constants;
import com.lvmama.common.enums.ErrorCodeEnum;
import com.lvmama.common.exception.BizException;
import com.lvmama.common.result.CodeMessage;
import com.lvmama.common.result.Result;
import com.lvmama.common.utils.BeanConvertionHelp;
import com.lvmama.common.utils.CheckParamsUtil;
import com.lvmama.common.utils.EncodeUtil;
import com.lvmama.common.utils.RandomUUIDUtil;
import com.lvmama.dao.rhino.system.RoleUserDao;
import com.lvmama.dao.rhino.system.UserDao;
import com.lvmama.pojo.base.Page;
import com.lvmama.pojo.base.ResultBase;
import com.lvmama.pojo.dto.rhino.system.UserDTO;
import com.lvmama.pojo.dto.rhino.system.UserQuery;
import com.lvmama.pojo.dto.rhino.system.UserQueryDTO;
import com.lvmama.pojo.entity.rhino.system.Role;
import com.lvmama.pojo.entity.rhino.system.User;
import com.lvmama.service.system.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleUserDao roleUserDao;

    @Override
    public Result<List<User>> queryUserList(UserQueryDTO query) {
        log.info("queryUserList start. query:{}",
                ToStringBuilder.reflectionToString(query, ToStringStyle.DEFAULT_STYLE));
        List<User> users = null;
        try {
            UserQuery example = new UserQuery();
            UserQuery.Criteria criteria = example.createCriteria().andDeletFlagEqualTo(Constants.DEL_FLAG);
            if (StringUtils.isNotBlank(query.getUsername())) {
                criteria.andLoginNameEqualTo(query.getUsername());
            }
            users = userDao.selectByExample(example);
        } catch (Exception e) {
            log.error("queryUserList error:", e.getMessage(), e);
            return Result.error(CodeMessage.SERVER_ERROR);
        }
        log.info("queryUserList end.");
        return Result.success(users);
    }

    @Override
    public Result<Page<User>> queryUserPage(UserQueryDTO query)  {
        log.info("queryUserPage start. query:{}",
                ToStringBuilder.reflectionToString(query, ToStringStyle.DEFAULT_STYLE));
        Page<User> page = new Page<>();
        try {
            UserQuery example = new UserQuery();
            example.createCriteria().andDeletFlagEqualTo(Constants.DEL_FLAG);
            int count = userDao.countByExample(example);
            example.setPageNo(query.getPageNo());
            example.setPageSize(query.getLimit());
            example.setStartRow(query.getStart());
            UserQuery.Criteria criteria = example.createCriteria().andDeletFlagEqualTo(Constants.DEL_FLAG);
            if (StringUtils.isNotBlank(query.getUsername())) {
                criteria.andLoginNameEqualTo(query.getUsername());
            }
            List<User> rows = userDao.selectByExample(example);
            //设置结果及分页对象
            if (null != rows && !rows.isEmpty()) {
                log.info("queryUserPage results:{}", count);
                log.info("queryUserPage rows:{}",
                        ToStringBuilder.reflectionToString(rows, ToStringStyle.DEFAULT_STYLE));
                page.setStart(query.getStart());
                page.setResults(count);
                page.setLimit(query.getLimit());
                page.setPage(query.getPage());
                page.setPageNo(query.getPageNo());
                page.setRows(rows);
                page.setIsSuccess(true);
            }
            //分页展示
            page.pageView("/user/userList", null);
        } catch (Exception e) {
            log.error("queryUserPage error:{}", e.getMessage(), e);
            page.setError("数据库查询用户分页失败");
            page.setErrorCode(e.getMessage());
            page.setErrorCode(e.getMessage());
            page.setResults(0);
        }
        log.info("queryUserPage end.");
        return Result.success(page);
    }

    @Override
    public Result<User> queryUserById(String id) {
        log.info("queryUserById start id:{}", id);
        User menu =null;
        try {
            menu = userDao.selectByPrimaryKey(id);
        } catch (Exception e) {
            log.error("queryUserById error:{}", e.getMessage(), e);
            return Result.error(CodeMessage.SERVER_ERROR);
        }
        log.info("queryUserById end.");
        return Result.success(menu);
    }

    @Override
    public Result<Integer> updateUserByUserDTO(UserDTO userDTO)  {
        log.info("updateUserByUserDTO start.menuDTO:{}",ToStringBuilder.reflectionToString(userDTO, ToStringStyle.DEFAULT_STYLE));
        int count = 0;
        try {
            CheckParamsUtil.check(userDTO, UserDTO.class, "id");
            User record = BeanConvertionHelp.copyBeanFieldValue(User.class, userDTO);
            record.setUseable("on".equals(userDTO.getIsEnable())?1:0);
            if (StringUtils.isNotBlank(userDTO.getPassword())) {
                //查询用户
                User user = userDao.selectByPrimaryKey(userDTO.getId());
                if (!user.getPassword().equals(userDTO.getPassword())) {
                    record.setPassword(EncodeUtil.encode(userDTO.getPassword()));
                    record.setIsReset(Constants.ONE);
                }
            }
            count = userDao.updateByPrimaryKeySelective(record);
            //更新角色用户
            //删除老的角色关系
            roleUserDao.deleteRoleUser(userDTO.getId());
            //用户所选的角色id
            List<String> roleUserIds = userDTO.getRoleIdList();
            User rec =new User();
            rec.setRoleIdList(roleUserIds);
            rec.setId(userDTO.getId());
            roleUserDao.insertBatch(rec);
        } catch (Exception e) {
            log.error("updateUserByUserDTO Exception:{}", e.getMessage(), e);
            return Result.error(CodeMessage.SERVER_ERROR);
        }
        log.info("updateUserByUserDTO end.");
        return Result.success(count);
    }

    @Override
    public Result<Integer> saveUserByUserDTO(UserDTO userDTO)  {
        log.info("saveUserByUserDTO start.menuDTO:{}",
                ToStringBuilder.reflectionToString(userDTO, ToStringStyle.DEFAULT_STYLE));
        int count = 0;
        try {
            User record = BeanConvertionHelp.copyBeanFieldValue(User.class, userDTO);
            record.setId(RandomUUIDUtil.getRadomUUID());
            record.setPassword(EncodeUtil.encode(userDTO.getPassword()));
            record.setDelFlag(Constants.DEL_FLAG);
            record.setUseable("on".equals(userDTO.getIsEnable())? 1 : 0);
            count = userDao.insertSelective(record);
            //保存角色用户
            count += roleUserDao.insertBatch(record);
        } catch (Exception e) {
            log.error("saveUserByUserDTO Exception:{}", e.getMessage(), e);
            return Result.error(CodeMessage.SERVER_ERROR);
        }
        log.info("saveUserByUserDTO end.");
        return Result.success(count);
    }

    @Override
    public Result<Boolean> deleteUserById(String id) {
        log.info("deleteUserById start. id:{}", id);
        int count = 0;
        try {
            User record = new User();
            record.setId(id);
            record.setDelFlag("1");
            count = userDao.updateByPrimaryKeySelective(record);
        } catch (Exception e) {
            log.error("deleteUserById Exception:{}", e.getMessage(), e);
            return Result.error(CodeMessage.SERVER_ERROR);
        }
        log.info("deleteUserById end,{} row(s) affected", count);
        return Result.success(true);
    }

    @Override
    public Result<User> queryUserRoleById(String id) {
        log.info("queryUserRoleById start id:{}", id);
        User user = null;
        try {
            user = userDao.selectByPrimaryKey(id);
            List<Role> roles = userDao.selectUserRoleById(id);
            if (user != null && roles != null && !roles.isEmpty()) {
                user.setRoles(roles);
            }
        } catch (Exception e) {
            log.error("queryUserRoleById error:{}", e.getMessage(), e);
            return  Result.error(CodeMessage.SERVER_ERROR);
        }
        log.info("queryUserRoleById end.");
        return Result.success(user);
    }

    @Override
    public ResultBase<User> queryUserAndRolesByUsername(String username) throws BizException {
        log.info("queryUserAndRolesByUsername start. username:{}", username);
        ResultBase<User> result = new ResultBase<>();
        try {
            User user = userDao.queryUserAndRolesByUsername(username);
            if (null != user) {
                result.setSuccess(true);
                result.setValue(user);
            }
        } catch (Exception e) {
            result.setErrorCode(ErrorCodeEnum.UNKOWN_ERROR.getCode());
            result.setErrorMsg(ErrorCodeEnum.UNKOWN_ERROR.getMsg());
            log.error("queryUserAndRolesByUsername error:{}", e.getMessage(), e);
        }
        log.info("queryUserAndRolesByUsername end.");
        return result;
    }

    @Override
    public Result<Integer> updateUserOperateDateByUserId(String userId) {
        log.info("updateUserOperateDateByUserId start, userId:{}", userId);
        try {
            User user = new User();
            user.setId(String.valueOf(userId));
            user.setLoginDate(new Date());
            userDao.updateByPrimaryKeySelective(user);
        } catch (Exception e) {
            log.error("updateUserOperateDateByUserId error:{}", e.getMessage(), e);
            return Result.error(CodeMessage.SERVER_ERROR);
        }
        log.info("updateUserOperateDateByUserId end.");
        return null;
    }

    @Override
    public Result<Integer> enableUserById(String id) {
        log.info("enableUserById start.id:{}", id);
        Integer isEnable = 0;
        try {
            //查询用户
            User user = userDao.selectByPrimaryKey(id);
            isEnable = user.getUseable();
            //更新
            User updateUser = new User();
            updateUser.setId(id);
            updateUser.setUseable(isEnable == 0 ? 1 : 0);
            userDao.updateByPrimaryKeySelective(updateUser);
        } catch (Exception e) {
            log.error("enableUserById Exception:{}", e.getMessage(), e);
            return Result.error(CodeMessage.SERVER_ERROR);
        }
        log.info("enableUserById end.");
        return Result.success(isEnable);
    }
}
